package flaud

import (
	"context"
	"github.com/flipped-aurora/gin-vue-admin/server/global"
	"github.com/flipped-aurora/gin-vue-admin/server/model/flaud"
	flaudReq "github.com/flipped-aurora/gin-vue-admin/server/model/flaud/request"
)

type CaseCauseService struct{}

// CreateCaseCause 创建案由管理记录
// Author [yourname](https://github.com/yourname)
func (CCService *CaseCauseService) CreateCaseCause(ctx context.Context, CC *flaud.CaseCause) (err error) {
	err = global.GVA_DB.Create(CC).Error
	return err
}

// DeleteCaseCause 删除案由管理记录
// Author [yourname](https://github.com/yourname)
func (CCService *CaseCauseService) DeleteCaseCause(ctx context.Context, ID string) (err error) {
	err = global.GVA_DB.Delete(&flaud.CaseCause{}, "id = ?", ID).Error
	return err
}

// DeleteCaseCauseByIds 批量删除案由管理记录
// Author [yourname](https://github.com/yourname)
func (CCService *CaseCauseService) DeleteCaseCauseByIds(ctx context.Context, IDs []string) (err error) {
	err = global.GVA_DB.Delete(&[]flaud.CaseCause{}, "id in ?", IDs).Error
	return err
}

// UpdateCaseCause 更新案由管理记录
// Author [yourname](https://github.com/yourname)
func (CCService *CaseCauseService) UpdateCaseCause(ctx context.Context, CC flaud.CaseCause) (err error) {
	err = global.GVA_DB.Model(&flaud.CaseCause{}).Where("id = ?", CC.ID).Updates(&CC).Error
	return err
}

// GetCaseCause 根据ID获取案由管理记录
// Author [yourname](https://github.com/yourname)
func (CCService *CaseCauseService) GetCaseCause(ctx context.Context, ID string) (CC flaud.CaseCause, err error) {
	err = global.GVA_DB.Where("id = ?", ID).First(&CC).Error
	return
}

// GetCaseCauseInfoList 分页获取案由管理记录
// Author [yourname](https://github.com/yourname)
func (CCService *CaseCauseService) GetCaseCauseInfoList(ctx context.Context, info flaudReq.CaseCauseSearch) (list []flaud.CaseCause, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	// 创建db
	db := global.GVA_DB.Model(&flaud.CaseCause{})
	var CCs []flaud.CaseCause
	// 如果有条件搜索 下方会自动创建搜索语句
	if info.StartCreatedAt != nil && info.EndCreatedAt != nil {
		db = db.Where("created_at BETWEEN ? AND ?", info.StartCreatedAt, info.EndCreatedAt)
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}
	var OrderStr string
	orderMap := make(map[string]bool)
	orderMap["cause_name"] = true
	orderMap["cause_type"] = true
	if orderMap[info.Sort] {
		OrderStr = info.Sort
		if info.Order == "descending" {
			OrderStr = OrderStr + " desc"
		}
		db = db.Order(OrderStr)
	}

	if limit != 0 {
		db = db.Limit(limit).Offset(offset)
	}

	err = db.Find(&CCs).Error
	return CCs, total, err
}
func (CCService *CaseCauseService) GetCaseCausePublic(ctx context.Context) {
	// 此方法为获取数据源定义的数据
	// 请自行实现
}
